class Wallet < ActiveRecord::Base
  has_many :user_wallets
  has_many :user, :through => :user_wallets

  has_many :tags, :dependent => :destroy
  has_many :amounts, :dependent => :destroy
  has_many :scheduled_records, :dependent => :destroy

  validates_presence_of :name

  accepts_nested_attributes_for :amounts, :reject_if => lambda { |a| a["value"].blank? }, :allow_destroy => true

  def default_amount(default_user_currency_code = nil)
    if default_user_currency_code
      return self.amounts.find_by_currency_code(default_user_currency_code) || self.amounts.build(:currency_code => default_user_currency_code)
    end

    !self.amounts(true).empty? && self.amounts[0] || self.amounts.build(:currency => Currency.first);
  end

  def amount_by_currency_code(default_user_currency_code, currency_code = nil)
    if currency_code && !currency_code.blank?
      amount = self.amounts.find_by_currency_code(currency_code) || self.amounts.create(:currency_code => currency_code)

      return amount if amount.valid?
    end

    self.default_amount(default_user_currency_code)
  end

  def currencies_codes
    self.amounts.map {|a| a.currency_code }
  end

  def as_json(options = nil)
    super(:methods => :amounts_hash)
  end

  def amounts_hash
    amounts.inject({}) do |h, a|
      h[a.currency_code] = a.value
      h
    end
  end

end
